package com.xauto.pioneer.appuser.activity.common;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.UriUtils;

import java.io.File;
import java.io.IOException;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;



/**
 * Created by lsx on 2017-11-28.
 */

public class TakeUserPhotoActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "TakeUserPhotoActivity";
    private TextView fromCarame;
    private TextView fromGarllary;
    private TextView cancelText;

    private static final int REQUEST_OPEN_CAMERA = 0x011;
    private static final int REQUEST_OPEN_GALLERY = 0x022;
    private static final int REQUEST_CROP_PHOTO = 0x033;
    private static final int REQUEST_PERMISSIONS = 0x044;
    //原图像 路径
    private static String imgPathOri;
    //裁剪图像 路径
    private static String imgPathCrop;
    //原图像 URI
    private Uri imgUriOri;
    //裁剪图像 URI
    private Uri imgUriCrop;
    @Override
    protected int getContentView() {
        return R.layout.ac_take_photo;
    }

    @Override
    protected void initView() {
        fromCarame = (TextView) findViewById(R.id.textview_dialog_take_picture);
        fromCarame.setOnClickListener(this);
        fromGarllary = (TextView) findViewById(R.id.textview_dialog_album);
        cancelText = (TextView) findViewById(R.id.textview_dialog_cancel);
        fromGarllary.setOnClickListener(this);
        cancelText.setOnClickListener(this);
        methodRequiresTwoPermission();
    }

    @Override
    protected void initData() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            imageType = !StringUtils.isBlank(bundle.getString(PARAM_IMAGE_TYPE)) ? bundle.getString(PARAM_IMAGE_TYPE) : DO_SMALL_IMAGE;
            aspectX = bundle.getInt(PARAM_ASPECT_X) != 0 ? bundle.getInt(PARAM_ASPECT_X) : 1;
            aspectY = bundle.getInt(PARAM_ASPECT_Y) != 0 ? bundle.getInt(PARAM_ASPECT_Y) : 1;
            outputX = bundle.getInt(PARAM_OUTPUT_X) != 0 ? bundle.getInt(PARAM_OUTPUT_X) : 360;
            outputY = bundle.getInt(PARAM_OUTPUT_Y) != 0 ? bundle.getInt(PARAM_OUTPUT_Y) : 360;
        }
    }

    @AfterPermissionGranted(1)//添加注解，是为了首次执行权限申请后，回调该方法
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            //已经申请过权限，直接调用相机
            // openCamera();
        } else {
            EasyPermissions.requestPermissions(this, "需要获取权限", 1, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                addPicToGallery(imgPathOri);
                cropPhoto(imgUriOri);
                break;
            case REQUEST_OPEN_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //打开相册会返回一个经过图像选择器安全化的Uri，直接放入裁剪程序会不识别，抛出[暂不支持此类型：华为7.0]
                        //formatUri会返回根据Uri解析出的真实路径
                        String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                        //根据真实路径转成File,然后通过应用程序重新安全化，再放入裁剪程序中才可以识别
                        cropPhoto(FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(imgPathSel)));
                        Log.e(TAG, "Kit_sel_path:" + imgPathSel);
                        Log.e(TAG, "Kit_sel_uri:" + Uri.fromFile(new File(imgPathSel)));
                    } else {
                        cropPhoto(imgUriSel);
                    }
                    Log.e(TAG, "openGalleryResult_imgUriSel:" + imgUriSel);
                }
                break;
            case REQUEST_CROP_PHOTO:
                addPicToGallery(imgPathCrop);
                revokeUriPermission(imgUriCrop, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                setResult(imgPathCrop);
                Log.e(TAG, "cropPhotoResult_imgPathCrop:" + imgPathCrop);
                Log.e(TAG, "cropPhotoResult_imgUriCrop:" + imgUriCrop.toString());
                break;
        }
    }
    /**
     * 裁剪图片
     * @param uri 需要 裁剪图像的Uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        File cropPhotoFile = null;
        try {
            cropPhotoFile = createCropImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (cropPhotoFile != null) {
//            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//                imgUriCrop = Uri.fromFile(cropPhotoFile);
//            }else{
//                imgUriCrop = FileProvider.getUriForFile(this, getPackageName() + ".provider", cropPhotoFile);
//            }

            //7.0 安全机制下不允许保存裁剪后的图片
            //所以仅仅将File Uri传入MediaStore.EXTRA_OUTPUT来保存裁剪后的图像
            imgUriCrop = Uri.fromFile(cropPhotoFile);

            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", true);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", false);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriCrop);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivityForResult(intent, REQUEST_CROP_PHOTO);

            Log.e(TAG, "cropPhoto_imgPathCrop:" + imgPathCrop.toString());
            Log.e(TAG, "cropPhoto_imgUriCrop:" + imgUriCrop.toString());
        }
    }
    /**
     * 创建裁剪图像保存的文件
     * @return
     * @throws IOException
     */
    private File createCropImageFile() throws IOException {
        String imgNameCrop = "avatar"+System.currentTimeMillis()+".png";
        File pictureDirCrop = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + getApplicationContext().getPackageName()
                + "/Files");
        if (!pictureDirCrop.exists()) {
            pictureDirCrop.mkdirs();
        }
        File image = File.createTempFile(
                imgNameCrop,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirCrop      /* directory */
        );
        imgPathCrop = image.getAbsolutePath();
        return image;
    }
    /**
     * 把图像添加进系统相册
     *
     * @param imgPath 图像路径
     */
    private void addPicToGallery(String imgPath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imgPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        sendBroadcast(mediaScanIntent);
    }
    public static final int UPLOAD_SUCCESS = 100;
    public static final int UPLOAD_IMG = 101;
    private void setResult(String Path) {
        Intent intent = new Intent();
        intent.putExtra("PATH", Path);
        setResult(UPLOAD_SUCCESS, intent);
        Log.e("照片",Path);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textview_dialog_album:
                openGallery();
                break;
            case R.id.textview_dialog_take_picture:
                openCamera();
                break;
            case R.id.textview_dialog_cancel:
                finish();
                break;
        }
    }
    private void openGallery() {
        Intent gallery_Intent = new Intent(Intent.ACTION_PICK, null);
        gallery_Intent.setType("image/*");
        startActivityForResult(gallery_Intent, REQUEST_OPEN_GALLERY);
    }
    /**
     * 打开相机
     * 7.0中如果需要调用系统(eg:裁剪)/其他应用，必须用FileProvider提供Content Uri，并且将Uri赋予读写的权限
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 打开相机
        File oriPhotoFile = null;
        try {
            oriPhotoFile = createOriImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (oriPhotoFile != null) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                imgUriOri = Uri.fromFile(oriPhotoFile);
            } else {
                imgUriOri = FileProvider.getUriForFile(this, getPackageName() + ".provider", oriPhotoFile);
            }
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
            startActivityForResult(intent, REQUEST_OPEN_CAMERA);

            // 动态grant权限
            // 如果在xml中已经定义android:grantUriPermissions="true"
            // 则只需要intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);即可
            //            List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            //            for (ResolveInfo resolveInfo : resInfoList) {
            //                String packageName = resolveInfo.activityInfo.packageName;
            //                grantUriPermission(packageName, imgUriOri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //            }
            Log.i(TAG, "openCamera_imgPathOri:" + imgPathOri);
            Log.i(TAG, "openCamera_imgUriOri:" + imgUriOri.toString());
        }
    }

    /**
     * 创建原图像保存的文件
     * @return
     * @throws IOException
     */
    private File createOriImageFile() throws IOException {
        String imgNameOri = "avatar"+System.currentTimeMillis()+".png";
        File pictureDirOri = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + getApplicationContext().getPackageName()
                + "/Files");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }
    /**
     * 图片处理方式：大图使用URI传递，小图使用bitmap传递
     */
    private String imageType = DO_SMALL_IMAGE;
    /**
     * option param key
     */
    public static final String PARAM_IMAGE_TYPE = "IMAGE_TYPE";
    /**
     * option param key-图片宽度比例
     */
    public static final String PARAM_ASPECT_X = "ASPECT_X";
    /**
     * option param key-图片高度比例
     */
    public static final String PARAM_ASPECT_Y = "ASPECT_Y";
    /**
     * option param key-图片宽度
     */
    public static final String PARAM_OUTPUT_X = "OUTPUT_X";
    /**
     * option param key-图片高度
     */
    public static final String PARAM_OUTPUT_Y = "OUTPUT_Y";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_BIG_IMAGE = "DO_BIG_IMAGE";
    /**
     * option param IMAGE_TYPE's value
     */
    public static final String DO_SMALL_IMAGE = "DO_SMALL_IMAGE";
    private int aspectX = 1;
    private int aspectY = 1;
    private int outputX = 360;
    private int outputY = 360;

    /***
     * 获取跳转Intent数据
     * @param mContext 上下文
     * @param imageType 图片类型：大图或小图
     * @param aspectX 图片宽度比例
     * @param aspectY 图片高度比例
     * @param outputX 图片宽度
     * @param outputY 图片高度
     * @return
     */
    public static Intent getTakePhotoStartIntent(Context mContext, String imageType,
                                                 int aspectX, int aspectY,
                                                 int outputX, int outputY) {
        Intent intent = new Intent(mContext, TakeUserPhotoActivity.class);
        intent.putExtra(TakeUserPhotoActivity.PARAM_IMAGE_TYPE, imageType);
        intent.putExtra(TakeUserPhotoActivity.PARAM_ASPECT_X, aspectX);
        intent.putExtra(TakeUserPhotoActivity.PARAM_ASPECT_Y, aspectY);
        intent.putExtra(TakeUserPhotoActivity.PARAM_OUTPUT_X, outputX);
        intent.putExtra(TakeUserPhotoActivity.PARAM_OUTPUT_Y, outputY);
        return intent;
    }
}
